package com.zhuang.sms.netty.decoder;

import com.zhuang.sms.proto.ChatMessageOuterClass.ChatMessage;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;


public class CustomProtobufDecoder extends ByteToMessageDecoder {

    private final ChatMessage clazz;

    public CustomProtobufDecoder(ChatMessage clazz) {
        this.clazz = clazz;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in.readableBytes() < 4) { // 假设这里先读取了一个长度前缀（uint32）
            return; // 数据不够，等待更多数据到来
        }

        int length = in.readInt(); // 获取消息长度
        if (in.readableBytes() < length) {
            in.resetReaderIndex(); // 重置读索引，等待完整消息到来
            return;
        }

        byte[] bytes = new byte[length];
        in.readBytes(bytes); // 读取指定长度的数据

        // 解码protobuf消息
        ChatMessage chatMessage = ChatMessage.parseFrom(bytes);

        // 处理接收到的Protobuf消息
        System.out.println("Received a protobuf message:");
        System.out.println("Sender: " + chatMessage.getSender());
        System.out.println("Message: " + chatMessage.getMessageText());
        System.out.println("Timestamp: " + chatMessage.getTimestamp());

        // 使用protobuf反序列化函数将字节数组转换为ChatMessage对象
//        ChatMessage chatMessage = (ChatMessage) clazz.getMethod("parseFrom", byte[].class).invoke(null, (Object) bytes);

        out.add(clazz); // 将反序列化的对象添加到输出列表中
    }
}